using System;
using System.Collections.Generic;
using System.Xml;
using UnityEditor;

public partial class GameCollection
{
    private readonly List<GameVO> gameList = new();
    private readonly Dictionary<string,TblGame.Conf> gameConfDict = new();
    private readonly HashSet<string> currGameNameSet = new();

    public IReadOnlyList<GameVO> GameList => gameList;

    public TblGame.Conf GetGameConf(string gameName)
    {
        return gameConfDict.GetValueOrDefault(gameName);
    }
    
    public void Load()
    {
        var gameTblPath = $"Assets/Proj/Games/s_common/Res/Conf/Table/TblGame.asset";
        var table = AssetDatabase.LoadAssetAtPath<TblGame>(gameTblPath);

        gameConfDict.Clear();
        foreach (var conf in table.Confs)
        {
            gameConfDict[conf.Desc] = conf;
        }

        var gameXmlPath = $"Assets/Proj/Configs/GameCollection.xml";

        gameList.Clear();
        currGameNameSet.Clear();

        try
        {
            var document = new XmlDocument();
            document.Load(gameXmlPath);
            var gamesNode = document.SelectSingleNode("GameCollection");
            if (gamesNode == null) return;

            var childNodes = gamesNode.ChildNodes;
            foreach (XmlNode node in childNodes)
            {
                var name = node.Attributes?["Name"].Value;
                if (string.IsNullOrEmpty(name)) continue;
                if (!gameConfDict.ContainsKey(name)) continue;
                if (!currGameNameSet.Add(name)) continue;
                var vo = new GameVO(name);
                vo.Parse(node);
                gameList.Add(vo);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}